package com.holi.hiteacher.net;

import com.holi.hiteacher.bean.JsonRootBean;
import com.holi.hiteacher.net.api.UserService;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @description:
 * @author: JoshuaWong E-mail:joshuawongchn@gmail.com
 * @date: 2016年12月28日 17:20
 * @version: 1.0
 */

public class UserModel {
    private UserService service;
    private MainViewModel viewModel;

    public UserModel(MainViewModel viewModel) {
        this.viewModel = viewModel;
        this.service = ServiceGenerator.createService(UserService.class);
    }

    public void getUser(String username) {
        Call<JsonRootBean> call = service.getUser(username);
        call.enqueue(new Callback<JsonRootBean>() {
            @Override
            public void onResponse(Call<JsonRootBean> call, Response<JsonRootBean> response) {
                JsonRootBean root = response.body();
                if (root == null) {
                    ResponseBody responseBody = response.errorBody();
                    if (responseBody != null) {
                        try {
                            viewModel.setText("responseBody = " + responseBody.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        viewModel.setText("responseBody = null");
                    }
                } else {
                    viewModel.setText("ID :" + root.getUser().getId() + "\n" +
                            "nickName :" + root.getUser().getNickName() + "\n" +
                            "loginPhone:" + root.getUser().getLoginPhone() + "\n" +
                            "loginPassword:" + root.getUser().getLoginPassword() + "\n" +
                            "picture:" + root.getUser().getPicture() + "\n" +
                            "createTime:" + root.getUser().getCreateTime()
                    );
                }
                viewModel.setPb(false);
            }

            @Override
            public void onFailure(Call<JsonRootBean> call, Throwable t) {
                viewModel.setText("t = " + t.getMessage());
                viewModel.setPb(false);
            }
        });
    }

}